import { defineStore } from "pinia";
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useAccessStore } from "./access";
import { getAuthCache, setAuthCache } from "@/utils/storage";
import { AllPermissions } from "@/auth/permissions";
import { resetRoutes } from "@/router/index";

export const useUserStore = defineStore("app-user", () => {
  const accessStore = useAccessStore();
  const userInfo = ref({});
  const router = useRouter();

  (function () {
    // 其他版本是有本地存储持久化 但是我没有加入
    // 我就在程序初始化的时候 做token
    const token = getAuthCache();
    if (token) {
      accessStore.setAccessToken(token);
    }
  })();

  function reset() {
    userInfo.value = {};
    accessStore.setIsAccessChecked(false);
    accessStore.setAccessCodes([]);
    accessStore.setAccessToken("");
    setAuthCache("");
  }

  function login(data) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({
          code: 200,
          data: {
            token: "token"
          },
          message: "登录成功"
        });
      }, 2000);
    }).then((res) => {
      if (res.code === 200) {
        accessStore.setAccessToken(res.data.token);
        setAuthCache(res.data.token);
        router.push({
          path: "/home"
        });
      } else {
        console.log("登录失败");
      }
    });
  }

  function getUserInfoAction() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({
          code: 200,
          data: {
            username: "登录人",
            roleCode: AllPermissions
          },
          message: "获取用户信息成功"
        });
      }, 0);
    }).then((res) => {
      console.log("userinfo", res.data);
      // this.userInfo = res.data;
      accessStore.setAccessCodes(res.data.roleCode);
      return res.data;
    });
  }

  async function logout() {
    // 移除本地存储
    setAuthCache("");
    // 重置store
    // accessStore.$reset();
    reset();
    // 重置用户信息
    userInfo.value = {};
    resetRoutes();
    await router.replace({
      path: "/login"
      // query: redirect
      //   ? {
      //       redirect: encodeURIComponent(router.currentRoute.value.fullPath)
      //     }
      //   : {}
    });
  }

  return {
    userInfo,
    login,
    logout,
    getUserInfoAction
  };
});
